package bgate.hung.activity;

import java.util.Vector;
import bgate.connector.DataTransfer;
import bgate.hung.workerclass.StaticBitmap;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ChoiseRoom extends Activity {
	private static final String TAG = "ChoiseRoomActivity";

	private DataTransfer dataTransfer = null;
	private IncommingMessage incommingMessage = null;
	private boolean isPushTask = false, isClicked = false;
	private RelativeLayout rooms[] = new RelativeLayout[10];
	private ImageView[] roomStatusImages = new ImageView[10];
	private TextView[] roomStatusTextViews = new TextView[10];
	private ProgressDialog progressDialog;
	private int[] roomIds = { R.id.room1_linearLayout_choise_room,
			R.id.room2_linearLayout_choise_room,
			R.id.room3_linearLayout_choise_room,
			R.id.room4_linearLayout_choise_room,
			R.id.room5_linearLayout_choise_room,
			R.id.room6_linearLayout_choise_room,
			R.id.room7_linearLayout_choise_room,
			R.id.room8_linearLayout_choise_room,
			R.id.room9_linearLayout_choise_room,
			R.id.room10_linearLayout_choise_room };
	private int[] roomStatusImageIds = { R.id.statusRoom1ImageView_choise_room,
			R.id.statusRoom2ImageView_choise_room,
			R.id.statusRoom2ImageView_choise_room,
			R.id.statusRoom3ImageView_choise_room,
			R.id.statusRoom4ImageView_choise_room,
			R.id.statusRoom4ImageView_choise_room,
			R.id.statusRoom5ImageView_choise_room,
			R.id.statusRoom6ImageView_choise_room,
			R.id.statusRoom7ImageView_choise_room,
			R.id.statusRoom8ImageView_choise_room,
			R.id.statusRoom9ImageView_choise_room,
			R.id.statusRoom10ImageView_choise_room };
	private int[] roomStatusTextViewIds = {
			R.id.statusRoom1TextView_choise_room,
			R.id.statusRoom2TextView_choise_room,
			R.id.statusRoom3TextView_choise_room,
			R.id.statusRoom4TextView_choise_room,
			R.id.statusRoom5TextView_choise_room,
			R.id.statusRoom6TextView_choise_room,
			R.id.statusRoom7TextView_choise_room,
			R.id.statusRoom8TextView_choise_room,
			R.id.statusRoom9TextView_choise_room,
			R.id.statusRoom10TextView_choise_room };
	private int[] ga_array, us_array, sm_array, isPlay_array, se_array;
	private String account = "";
	private int room;
	private boolean receivedUS = false, receivedSM = false,
			receivedISPLAY = false, receivedSE = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		dataTransfer = DataTransfer.getInstance();
		if (incommingMessage == null)
			incommingMessage = new IncommingMessage(dataTransfer.getOutQueue());
		if (!isPushTask && incommingMessage != null) {
			dataTransfer.putTask(incommingMessage);
			isPushTask = true;
		}

		Intent intent = getIntent();
		account = intent.getStringExtra("ACCOUNT");
		ga_array = intent.getIntArrayExtra("GA_ARRAY");

		setContentView(R.layout.choise_room_layout);

		progressDialog = new ProgressDialog(ChoiseRoom.this);
		progressDialog.setMessage("Xin chờ ...");

		for (int i = 0; i < 10; i++) {
			rooms[i] = (RelativeLayout) findViewById(roomIds[i]);
			roomStatusImages[i] = (ImageView) findViewById(roomStatusImageIds[i]);
			roomStatusTextViews[i] = (TextView) findViewById(roomStatusTextViewIds[i]);

			roomStatusImages[i]
					.setImageBitmap(getStatusRoomBitmap(ga_array[i]));
			roomStatusTextViews[i].setText(getStatusRoomString(ga_array[i]));

			final int roomId = i;

			rooms[i].setOnTouchListener(new OnTouchListener() {

				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					int action = event.getAction();
					if (action == MotionEvent.ACTION_DOWN) {
						rooms[roomId]
								.setBackgroundResource(R.drawable.room_clicked);
					} else if (action == MotionEvent.ACTION_UP
							|| action == MotionEvent.ACTION_CANCEL) {
						rooms[roomId]
								.setBackgroundResource(R.drawable.room_row);
						if (action == MotionEvent.ACTION_UP) {
							if (!isClicked) {
								isClicked = true;
								progressDialog.show();
								room = roomId + 1;
								sendSERequest(roomId);
							}
						}
					}
					return true;
				}
			});
		}
	}

	private void setRoomStatus() {
		for (int i = 0; i < 10; i++) {
			roomStatusImages[i]
					.setImageBitmap(getStatusRoomBitmap(ga_array[i]));
			roomStatusTextViews[i].setText(getStatusRoomString(ga_array[i]));
		}
	}

	public void onResume() {
		super.onResume();
		isClicked = false;
		receivedUS = false;
		receivedSM = false;
		receivedISPLAY = false;
		receivedSE = false;
		dataTransfer = DataTransfer.getInstance();
		if (incommingMessage == null)
			incommingMessage = new IncommingMessage(dataTransfer.getOutQueue());
		if (!isPushTask && incommingMessage != null) {
			dataTransfer.putTask(incommingMessage);
			isPushTask = true;
		}
	}

	public void onPause() {
		super.onPause();
		if (isPushTask) {
			dataTransfer.removeTask(incommingMessage);
			isPushTask = false;
		}
		incommingMessage = null;
	}

	public void onBackPressed() {
		super.onBackPressed();
		dataTransfer.requestData("}RGA|&");
		finish();
	}

	private void sendSERequest(int i) {
		dataTransfer.requestData("}SE|" + Integer.toString(i) + "&");
	}

	private Bitmap getStatusRoomBitmap(int n) {
		if (n == 0)
			return StaticBitmap.getStatusRoom0Image();
		else if ((n > 0) && (n < 20))
			return StaticBitmap.getStatusRoom1Image();
		else if ((n >= 20) && (n < 40))
			return StaticBitmap.getStatusRoom2Image();
		else if ((n >= 40) && (n < 60))
			return StaticBitmap.getStatusRoom3Image();
		else if ((n >= 60) && (n < 80))
			return StaticBitmap.getStatusRoom4Image();
		else
			return StaticBitmap.getStatusRoom5Image();
	}

	private String getStatusRoomString(int n) {
		String s = "";
		s += Integer.toString(n) + "-100";
		return s;
	}

	final Handler showMessageEnterRoom = new Handler() {
		public void handleMessage(Message msg) {
			Toast.makeText(ChoiseRoom.this,
					"Vào phòng " + Integer.toString(room), Toast.LENGTH_SHORT)
					.show();
		}
	};

	private void enterChoiseTable() {
		System.out.println("----------Vao phong----------");
		Intent intent = new Intent(this, ChoiseTable.class);
		intent.putExtra("US_ARRAY", us_array);
		intent.putExtra("SM_ARRAY", sm_array);
		intent.putExtra("ISPLAY_ARRAY", isPlay_array);
		intent.putExtra("SE_ARRAY", se_array);
		intent.putExtra("ACCOUNT", account);
		progressDialog.cancel();
		startActivity(intent);
	}

	private class IncommingMessage implements Runnable {
		private final Vector mInQueue;

		public IncommingMessage(Vector inQueue) {
			this.mInQueue = inQueue;
		}

		public void run() {

			try {
				Thread.sleep(10);
				if (mInQueue.size() > 0) {

					String data = (String) mInQueue.elementAt(0);
					mInQueue.removeElementAt(0);
					Log.d(TAG, data);
					Vector<String> tempResultData = splitString(data, '}');
					for (int k = 0; k < tempResultData.size(); k++) {
						Vector<String> resultData = splitString(
								tempResultData.elementAt(k), '|');
						for (int i = 0; i < resultData.size(); i++) {
							String s = resultData.elementAt(i);
							if (s.equals("US")) {
								us_array = new int[resultData.size() - i - 1];
								int index = 0;
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									us_array[index] = Integer.valueOf(s);
									index++;
								}
								receivedUS = true;
							}

							if (s.equals("SM")) {
								sm_array = new int[resultData.size() - i - 1];
								int index = 0;
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									sm_array[index] = Integer.valueOf(s);
									index++;
								}
								receivedSM = true;
							}

							if (s.equals("ISPLAY")) {
								isPlay_array = new int[resultData.size() - i
										- 1];
								int index = 0;
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									isPlay_array[index] = Integer.valueOf(s);
									index++;
								}
								receivedISPLAY = true;
							}

							if (s.equals("SE")) {
								se_array = new int[resultData.size() - i - 1];
								int index = 0;
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									se_array[index] = Integer.valueOf(s);
									index++;
								}
								receivedSE = true;
								if (receivedUS && receivedSM && receivedISPLAY
										&& receivedSE)
									enterChoiseTable();
							}

							if (s.equals("GA")) {
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									if (j < ga_array.length) {
										ga_array[j] = Integer.valueOf(s);
									}
								}
								setRoomStatus();
							}
						}
					}
				}
			} catch (InterruptedException ex) {
				Log.d(TAG, ex.toString());
			} catch (NullPointerException ex) {
				Log.d(TAG, ex.toString());
			}

		}

	}

	private Vector<String> splitString(String string, char delimiter) {
		Vector<String> mResult = new Vector<String>();
		TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(
				delimiter);

		// Once per string to split
		splitter.setString(string);
		for (String s : splitter) {
			String temp = "";
			for (int i = 0; i < s.length(); i++) {
				if (s.charAt(i) != '}' && s.charAt(i) != '&')
					temp += s.charAt(i);
			}
			mResult.addElement(temp);
		}

		return mResult;
	}
}
